<script type="text/x-template" id="template-main_favorites">
    <div>
        <div class="div-main"  style="margin-bottom: 10px;display: flex;justify-content: space-between;">
            <div>
                <el-button type="primary" size="mini" @click="handleCollection('add')">新建收藏夹</el-button>
                <el-button v-if="showType==='favorites'" @click="deleteHandle(selectionList)" :disabled="!selectionList.length" size="mini">删除</el-button>
                <el-button v-else @click="cancelFavorites(selectionList)" :disabled="!selectionList.length" size="mini">取消收藏</el-button>
            </div>
            <div>
                <el-button @click="back" icon="iconfont icon-fanhui" size="mini" v-if="showType==='file' && form.collectionId">返回</el-button>
            </div>
        </div>
        <div class="div-main">
            <el-form :model="form" ref="searchForm" label-width="70px" size="mini" style="margin-bottom: 20px;">
                <el-row type="flex" justify="space-between">
                    <el-col :span="6">
                        <el-form-item label="收藏夹" prop="collectionName">
                            <el-input v-model="form.collectionName" :disabled="false" :style="{width:  '100%'}" :clearable="true" placeholder="请输入收藏夹"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6" >
                        <el-form-item label="文档名称" prop="fileName">
                            <el-input v-model="form.fileName" :disabled="false" :style="{width:  '100%'}" :clearable="true" placeholder="请输入文档名称"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6" style="text-align: right;">
                        <el-button type="primary" icon="el-icon-search" @click="search" size="mini">查询</el-button>
                        <el-button @click="rest" icon="el-icon-refresh" size="mini">重置</el-button>
                    </el-col>
                </el-row>
            </el-form>
            <el-table v-loading="loading" ref="multipleTable" border :data="dataList" tooltip-effect="dark" @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="40"></el-table-column>
                <el-table-column label="名称" align="left" width="340" show-overflow-tooltip>
                    <template slot-scope="scope,text">
                        <span v-if="showType==='favorites'" @click="viewsHandle(scope.row)" style="cursor: pointer;">
                            <i class="el-icon-folder"  style="color:orange"></i>
                            {{ scope.row.name }}
                        </span>
                        <span v-else>
                            <i class="el-icon-picture"  style="color:orange" v-if="scope.row.fileExt=='png'||scope.row.fileExt=='jpg'"></i>
                            <i class="el-icon-folder"  style="color:orange" v-else-if="!scope.row.fileExt"></i>
                            <i class="el-icon-document"  style="color:cornflowerblue" v-else></i>
                            {{ scope.row.fileName }}
                        </span>
                    </template>
                </el-table-column>
                <el-table-column label="创建时间" align="center" prop="createdDate" width="320"  v-if="showType==='favorites'"></el-table-column>
                <el-table-column label="创建人" align="center" prop="createdUserName" width="100" v-if="showType==='file'"></el-table-column>
                <el-table-column label="收藏时间" align="center" prop="staredDate" width="210" v-if="showType==='file'"></el-table-column>
                <el-table-column label="文件路径" align="center"  width="220" v-if="showType==='file'" show-overflow-tooltip>
                    <template slot-scope="scope">
                        <span>{{scope.row.fileStatus && scope.row.fileStatus==='DELETED'? '该文档已删除': scope.row.filePath}}</span>
                    </template>
                </el-table-column>
                <el-table-column label="操作" align="center">
                    <template slot-scope="scope">
                        <span v-if="showType==='favorites'">
                            <el-link type="primary" :underline="false" @click="viewsHandle(scope.row)">查看</el-link>
                            <el-link type="primary" :underline="false" @click="handleCollection('edit', scope.row)">修改名称</el-link>
                            <el-link type="primary" :underline="false" @click="deleteHandle(scope.row)">删除</el-link>
                        </span>
                        <span v-else-if="showType==='file' && scope.row.fileStatus!=='DELETED'">
                            <el-link type="primary" :underline="false" v-if="scope.row.fileExt" @click="preview(scope.row)">预览</el-link>
                            <el-link type="primary" :underline="false" @click="cancelFavorites(scope.row)">取消收藏</el-link>
                        </span>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination
                    background
                    :page-sizes="[10,20,30,40,50,100]"
                    layout="total, sizes, prev, pager, next, jumper"
                    :current-page="currentPage"
                    :page-size="pageSize"
                    :total="total"
                    class="ms-pagination"
                    @current-change='currentChange'
                    @size-change="sizeChange">
            </el-pagination>
        </div>
        <div id="viewerImage" style="display: none;"></div>
        <el-dialog :title="dialogType==='add'?'新建收藏夹':'修改名称'" :visible.sync="dialogVisible">
            <el-form :model="dialogForm" :rules="rules" ref="ruleForm">
                <el-form-item label="收藏夹名称" :label-width="formLabelWidth" prop="name">
                    <el-input placeholder="请输入" v-model="dialogForm.name" autocomplete="off"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="resetForm()">取 消</el-button>
                <el-button type="primary" @click="submitForm()">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</script>
<script>
    var MainMyFavorites = {
        template: '#template-main_favorites',
        data: function () {
            return {
                count: 0,
                tabValue: "1",
                conditions: [],
                contentCategoryIdOptions: [],
                dataList: [],
                //文章列表
                selectionList: [],
                //文章列表选中
                total: 0,
                //总记录数量
                pageSize: 10,
                //页面数量
                currentPage: 1,
                //初始页
                manager: ms.manager,
                formLabelWidth: '100px',
                loadState: false,
                loading: true,
                dialogVisible: false,
                dialogType: 'add',
                //加载状态
                emptyText: '',
                //提示文字
                contentTypeOptions: [],
                contentDisplayOptions: [{
                    "value": "0",
                    "label": "是"
                }, {
                    "value": "1",
                    "label": "否"
                }],
                showType: 'favorites', // favorites收藏夹，file 文档
                //搜索表单
                form: {
                    collectionId: null,
                    collectionName: null,
                    fileName: null
                },
                dialogForm: {
                    name: ''
                },
                rules: {
                    name: [
                        { required: true, message: '请输入收藏夹名称', trigger: 'change' }
                    ]
                },
                viewer: null
            }
        },
        methods: {
            //查询列表
            list: function () {
                var that = this;
                that.loading = true;
                that.loadState = false;
                if (Object.keys(this.form).length>0 && (this.form.fileName || this.form.collectionId) ) {
                    this.showType = 'file';
                } else {
                    this.showType = 'favorites';
                }
                var page = {
                    pageNo: that.currentPage,
                    pageSize: that.pageSize
                };
                var form = JSON.parse(JSON.stringify(that.form));

                for (var key in form) {
                    if (!form[key]) {
                        delete form[key];
                    }
                }

                history.replaceState({
                    form: form,
                    page: page
                }, "");
                //筛选栏目类型，1=列表
                ms.http.post(ms.manager + "/collection/list.do", Object.assign({}, form, page), {
                    headers: {
                        'Content-Type': 'application/json'
                    }
                }).then(function (res) {
                    if (that.loadState) {
                        that.loading = false;
                    } else {
                        that.loadState = true;
                    }

                    if (!res.result || res.data.total <= 0) {
                        that.emptyText = '暂无数据';
                        that.dataList = [];
                        that.total = 0;
                    } else {
                        that.emptyText = '';
                        that.total = res.data.total;
                        that.dataList = res.data.records;
                    }
                }).finally(function () {
                    that.loading = false;
                });
                setTimeout(function () {
                    if (that.loadState) {
                        that.loading = false;
                    } else {
                        that.loadState = true;
                    }
                }, 500);
            },
            search: function (data) {
                this.currentPage = 1;
                this.list();
            },
            //重置表单
            rest: function () {
                this.$refs.searchForm.resetFields();
                this.list();
            },
            //pageSize改变时会触发
            sizeChange: function (pagesize) {
                this.loading = true;
                this.pageSize = pagesize;
                this.list();
            },
            //currentPage改变时会触发
            currentChange: function (currentPage) {
                this.loading = true;
                this.currentPage = currentPage;
                this.list();
            },
            // 查看
            viewsHandle: function (row) {
                this.$set(this.form, 'collectionId', row.id);
                this.showType = 'file';
                this.list();
            },
            // 返回
            back: function (val) {
                this.$set(this.form, 'collectionId', null);
                this.showType = 'favorites';
                this.list();
            },
            //列表选中
            handleSelectionChange: function (val) {
                this.selectionList = val;
            },
            // 新建收藏夹、名称修改
            handleCollection: function (handleType, row) {
                // this.dialogForm = Object.assign({}, this.dialogForm, row);
                this.dialogType = handleType;
                this.dialogVisible = true;
                if(handleType==='edit') {
                    this.$set(this.dialogForm, 'name', row.name);
                    this.$set(this.dialogForm, 'id', row.id);
                } else {
                    this.$set(this.dialogForm, 'name', null);
                    this.$set(this.dialogForm, 'id', null);
                }
            },
            // 新建收藏夹确认提交、名称修改确认提交
            submitForm: function() {
                var that = this;
                that.$refs.ruleForm.validate(function (valid) {
                    if (valid) {
                        var sform = {};
                        var api;
                        if (that.dialogType==='add') {
                            api = "/collection/create.do";
                            sform = {name: that.dialogForm.name}
                        } else if(that.dialogType==='edit') {
                            api = "/collection/modify.do";
                            sform = {collectionId: that.dialogForm.id, collectionName: that.dialogForm.name}
                        }
                        ms.http.post(ms.manager + api, sform, {
                            headers: {
                                'Content-Type': 'application/json'
                            }
                        }).then(function (res) {
                            if (res.result) {
                                if (res.data && Object.keys(res.data).length>0 && !res.data.exists) {
                                    that.$message.success('操作成功!');
                                    that.list();
                                    that.dialogVisible = false
                                } else if (res.data && Object.keys(res.data).length>0 && res.data.exists)  {
                                    that.$message.warning('名称已存在!');
                                } else {
                                    that.$message.success('操作成功!');
                                }
                            } else {
                                that.$message.error('操作失败!');
                            }
                        });
                    } else {
                        return false;
                    }
                });
            },
            // 新建收藏夹取消、名称修改取消
            resetForm: function() {
                this.dialogVisible = false
            },
            //删除、批量删除
            deleteHandle: function (row) {
                var that = this;
                that.$confirm('确认删除吗?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(function () {
                    var form = {
                        collectionId: row.length? row.map( function(v) {return v.id}) :[row.id]
                    };
                    ms.http.post(ms.manager + "/collection/delete.do", form, {
                        headers: {
                            'Content-Type': 'application/json'
                        }
                    }).then(function (res) {
                        if (res.result) {
                            that.$message.success('操作成功');
                            that.list();
                        } else {
                            that.$message.warning('操作失败');
                        }
                    });
                })
            },
            //取消收藏
            cancelFavorites: function (row) {
                var that = this;
                that.$confirm('确认取消收藏吗?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(function () {
                    var form = {
                        ids: row.length? row.map( function(v) {return v.starId}) :[row.starId]
                    };
                    ms.http.post(ms.manager + "/collection/cancel.do", form, {
                        headers: {
                            'Content-Type': 'application/json'
                        }
                    }).then(function (res) {
                        if (res.result) {
                            that.$message.success('取消收藏成功');
                            that.list();
                        } else {
                            that.$message.warning('取消收藏失败');
                        }
                    });
                })
            },
            // 预览
            preview: function (row) {
                if(row.fileExt=='png'||row.fileExt=='jpg'||row.fileExt=='doc'||row.fileExt=='docx'||row.fileExt=='xls'||row.fileExt=='xlsx'||row.fileExt=='pdf'||row.fileExt=='txt') {
                    var filePath = row.fileUrl;
                    window.parent.indexVue.onlinePreview(filePath);
                    ms.http.get(ms.manager + "/log/record/view?fileId="+row.fileId).then(function(res){
                    });
                } else {
                    this.downloadFile(row)
                    // var that = this;
                    // ms.http.post(ms.manager + "/cms/document/download.do", {id:row.fileId},{
                    //     headers: {
                    //         'Content-Type': 'application/json'
                    //     },
                    //     responseType:'blob'
                    // }).then(function (res) {
                    //     if(row.fileExt=='png'||row.fileExt=='jpg') {
                    //         that.blobToBase64(res).then(imgSrc => {
                    //             // 转化后的base64
                    //             var html = "<img src="+imgSrc+" width='50' alt="+row.fileName+" title="+ms.fileUrl+row.filePath+">";
                    //             document.getElementById('viewerImage').innerHTML = html;
                    //             that.viewer.show()
                    //         })
                    //     } else if(row.fileExt!='png'&&row.fileExt!='jpg')  {
                    //         if(!row.fileExt){
                    //             that.downLoadMix(res,row.fileName+".zip")
                    //         }else{
                    //             that.downLoadMix(res,row.fileName)
                    //         }
                    //     }
                    // }).catch(function (err) {
                    //     that.$message.error('失败');
                    // });
                }
            },
            // 下载
            downloadFile: function (row) {
                var that = this;
                ms.http.post(ms.manager + "/cms/document/download.do", {id:row.fileId},{
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    responseType:'blob'

                }).then(function (res) {
                    if(!row.fileExt){
                        that.downLoadMix(res,row.fileName+".zip")
                    }else{
                        that.downLoadMix(res,row.fileName)
                    }
                }).catch(function (err) {
                    that.$message.error('下载失败');
                });
            },
            downLoadMix:function(res, fileName){//new Blob([res],{ type: "application/zip" }
                var blob = new Blob([res]); //res为从后台返回的数据
                if ("msSaveOrOpenBlob" in navigator) {
                    window.navigator.msSaveOrOpenBlob(blob, fileName);
                } else {
                    var link = document.createElement('a');
                    var body = document.querySelector('body');
                    link.href = window.URL.createObjectURL(blob);
                    link.download = fileName;
                    link.style.display = 'none';
                    body.appendChild(link);
                    link.click();
                    body.removeChild(link);
                    window.URL.revokeObjectURL(link.href)
                }
            },
            blobToBase64(blob) {
                return new Promise((resolve, reject) => {
                    const fileReader = new FileReader();
                    fileReader.onload = (e) => {
                        resolve(e.target.result);
                    };
                    fileReader.readAsDataURL(blob);
                    fileReader.onerror = () => {
                        reject(new Error('blobToBase64 error'));
                    };
                });
            }
        },
        created: function () {
            this.list();
        },
        mounted: function () {
            // this.$nextTick(() => {
            //     var that = this;
            //     var maxOffsetPercentage = 0.9;
            //     that.viewer = new Viewer(document.getElementById('viewerImage'), {
            //         // backdrop: 'static',
            //         navbar: false,
            //         className: 'viewer-container-customize',
            //         container: window.parent.document.body,
            //         show: function (){
            //             that.viewer.update()
            //         }
                    // move: function (event) {
                    //     var viewerData = viewer.viewerData;
                    //     var imageData = viewer.imageData;
                    //     var maxOffsetHorizontal = viewerData.width * maxOffsetPercentage;
                    //     var maxOffsetVertical = viewerData.height * maxOffsetPercentage;
                    //     var detail = event.detail;
                    //     var left = detail.x;
                    //     var top = detail.y;
                    //     var right = viewerData.width - (left + imageData.width);
                    //     var bottom = viewerData.height - (top + imageData.height);
                    //
                    //     if (
                    //         // Move left
                    //         (detail.x < detail.oldX && right > 0 && right > maxOffsetHorizontal)
                    //
                    //         // Move right
                    //         || (detail.x > detail.oldX && left > 0 && left > maxOffsetHorizontal)
                    //
                    //         // Move up
                    //         || (detail.y < detail.oldY && bottom > 0 && bottom > maxOffsetVertical)
                    //
                    //         // Move down
                    //         || (detail.y > detail.oldY && top > 0 && top > maxOffsetVertical)
                    //     ) {
                    //         event.preventDefault();
                    //     }
                    // },
                    // zoomed: function (event) {
                    //     var detail = event.detail;
                    //
                    //     // Zoom out
                    //     if (detail.ratio < detail.oldRatio) {
                    //         var viewerData = viewer.viewerData;
                    //         var imageData = viewer.imageData;
                    //         var maxOffsetHorizontal = viewerData.width * maxOffsetPercentage;
                    //         var maxOffsetVertical = viewerData.height * maxOffsetPercentage;
                    //         var left = imageData.x;
                    //         var top = imageData.y;
                    //         var right = viewerData.width - (left + imageData.width);
                    //         var bottom = viewerData.height - (top + imageData.height);
                    //         var x = 0;
                    //         var y = 0;
                    //
                    //         if (right > 0 && right > maxOffsetHorizontal) {
                    //             x = maxOffsetHorizontal - right;
                    //         }
                    //
                    //         if (left > 0 && left > maxOffsetHorizontal) {
                    //             x = maxOffsetHorizontal - left;
                    //         }
                    //
                    //         if (bottom > 0 && bottom > maxOffsetVertical) {
                    //             y = bottom - maxOffsetVertical;
                    //         }
                    //
                    //         if (top > 0 && top > maxOffsetVertical) {
                    //             y = top - maxOffsetVertical;
                    //         }
                    //
                    //         // Move the image into view if it is invisible
                    //         if (x !== 0 || y !== 0) {
                    //             viewer.move(x, y);
                    //         }
                    //     }
                    // },
            //     });
            // });
        }
    }
</script>
